/*
 * Created on Jun 12, 2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package de.localsport.util;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

import java.util.Properties;
import java.util.Date;

/**
 * @author mino
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class Mailer {
	
	private static boolean debug = false;

//  private static String emailFrom = "noreply@localsport.de";

	private static String emailFrom = "tippspiel@keidel.info";	
	private static String host = "smtp.1und1.de";
        private static boolean bAuthMode = true;
        private static String sUserName = "tippspiel@keidel.info";
        private static String sPassword = "btwm2010";
	
	int send(String to, String messageText) {
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", "25");
		props.put("mail.smtp.auth", "true");
		
		int sendResult = 0;
		
		Session session = Session.getDefaultInstance(props);
		
		try {
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(emailFrom));
			InternetAddress to_address = new InternetAddress(to);
			message.setRecipient(Message.RecipientType.TO, to_address);
			message.setSubject("Welcome to BT IT&PS WM Portal");
			message.setSentDate(new Date());
			
			MimeBodyPart mbp = new MimeBodyPart();
			mbp.setText(messageText);
			
			Multipart mp = new MimeMultipart();
			mp.addBodyPart(mbp);
			
			message.setContent(mp);

			if (bAuthMode) {
message.saveChanges(); // implicit with send()
Transport transport = session.getTransport("smtp");
System.out.println("Test1");
transport.connect(host, sUserName, sPassword);
System.out.println("Test2");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
			} else {			
				Transport.send(message);
			}
			
		} catch (MessagingException mex) {
			System.out.println("Messaging exception: " + mex.toString());
			sendResult = 1;
		}
		
		return sendResult;
	}

	public int sendPassword (String to, String passwd) {
				
		StringBuffer sb = new StringBuffer();
		sb.append("Ihr Passwort: " + passwd);
		
		if (! debug) {
			return send(to, sb.toString());

		} else {
			System.out.println("EMAIL: Sending email was skipped. Recipient:" + to);
			System.out.println("EMAIL: Message was:\n" + sb.toString());
			return 0;
		}
	}
	
	public static void main(String args[]) {
		Mailer m = new Mailer();
		m.send(new String(args[0]), args[1]);
	}
}
